import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import '../model/chat_message.dart';
import '../utils/api.dart';

class ChatPage extends StatefulWidget {
  final String userId; // 对方用户ID
  final String nickname;
  final String myId; // 当前登录用户ID

  const ChatPage({
    super.key,
    required this.nickname,
    required this.userId,
    required this.myId,
  });

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final List<ChatMessage> messages = [];
  final TextEditingController _controller = TextEditingController();

  late WebSocketChannel _channel;

  @override
  void initState() {
    super.initState();
    _loadHistory();
    _connectWebSocket();
  }

  @override
  void dispose() {
    _channel.sink.close();
    _controller.dispose();
    super.dispose();
  }

  Future<void> _loadHistory() async {
    try {
      final response = await Api.get(
        '/message/history',
        params: {
          'userId': widget.myId,
          'peerId': widget.userId,
          'page': 1.toString(),
          'pageSize': 20.toString(),
        },
      );

      if (response['code'] == 0) {
        final List data = response['data'] ?? [];
        final loadedMessages = data
            .map((e) => ChatMessage.fromJson(e, widget.myId))
            .toList();
        setState(() {
          messages.addAll(loadedMessages);
        });
      } else {
        debugPrint('加载历史消息失败: ${response['msg']}');
      }
    } catch (e) {
      debugPrint('加载历史消息异常: $e');
    }
  }

  void _connectWebSocket() {
    _channel = WebSocketChannel.connect(
      Uri.parse('${Api.wsBaseUrl}/chat?userId=${widget.myId}'),
    );

    _channel.stream.listen(
      (event) {
        debugPrint('收到WebSocket消息: $event');
        final msgMap = json.decode(event);
        final newMsg = ChatMessage.fromJson(msgMap, widget.myId);
        if (newMsg.senderId == widget.userId ||
            newMsg.receiverId == widget.userId) {
          setState(() {
            messages.add(newMsg);
          });
        }
      },
      onDone: () {
        debugPrint('WebSocket连接关闭，尝试重连');
        Future.delayed(const Duration(seconds: 3), _connectWebSocket);
      },
      onError: (error) {
        debugPrint('WebSocket异常: $error，尝试重连');
        Future.delayed(const Duration(seconds: 3), _connectWebSocket);
      },
    );
  }

  Future<void> _sendMessage(String text) async {
    if (text.trim().isEmpty) return;

    final newMsg = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      senderId: widget.myId,
      receiverId: widget.userId,
      content: text.trim(),
      timestamp: DateTime.now(),
      isSelf: true,
    );

    setState(() {
      messages.add(newMsg);
    });
    _controller.clear();

    try {
      final response = await Api.post(
        '/message/send',
        body: {'toUserId': widget.userId, 'content': text.trim()},
      );

      if (response['code'] != 0) {
        debugPrint('消息发送失败: ${response['msg']}');
        // 可以做失败重试或提示
      }
    } catch (e) {
      debugPrint('消息发送异常: $e');
      // 可以做失败重试或提示
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('与 ${widget.nickname} 聊天')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(10),
              itemCount: messages.length,
              itemBuilder: (context, index) {
                final msg = messages[index];
                return Align(
                  alignment: msg.isSelf
                      ? Alignment.centerRight
                      : Alignment.centerLeft,
                  child: Container(
                    margin: const EdgeInsets.symmetric(vertical: 4),
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: msg.isSelf ? Colors.blue : Colors.grey[300],
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      msg.content,
                      style: TextStyle(
                        color: msg.isSelf ? Colors.white : Colors.black87,
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
          const Divider(height: 1),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            color: Colors.grey[100],
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _controller,
                    decoration: const InputDecoration(
                      hintText: '输入消息...',
                      border: InputBorder.none,
                    ),
                    onSubmitted: _sendMessage,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: () => _sendMessage(_controller.text),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
